package com.example.java.kafka.consumer;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Properties;

public class CustomConsumer {
    public static void main(String[] args) {
        // 创建消费者的配置对象
        KafkaConsumer<String, String> kafkaConsumer = CustomConsumer.getCustomConsumer();
        // 注册要消费的主题（可以消费多个主题）
//        ArrayList<String> topics = new ArrayList<>();
//        topics.add("consumer1");
//        kafkaConsumer.subscribe(topics);
        // 消费某个主题的某个分区的数据
        ArrayList<TopicPartition> topicPartitions = new ArrayList<>();
        topicPartitions.add(new TopicPartition("consumer1", 0));
        kafkaConsumer.assign(topicPartitions);
        // 拉取数据打印
        while (true) {
            // 设置 1s 中消费一批数据
            ConsumerRecords<String, String> consumerRecords = kafkaConsumer.poll(Duration.ofSeconds(1));
            // 打印消费到的数据
            for (ConsumerRecord<String, String> consumerRecord : consumerRecords) {
                System.out.println("消费数据：" + consumerRecord);
            }
        }
    }

    private static KafkaConsumer<String, String> getCustomConsumer() {
        Properties properties = new Properties();
        // 给消费者配置对象添加参数
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "43.139.50.31:9092");
        // 配置序列化，必须
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        // 配置消费者组，组名任意起，但必须存在！必须存在！必须存在！
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "consumer_group");
        // 创建消费者对象
        return new KafkaConsumer<>(properties);
    }

}